﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using log4net;
using RentHouse.Service.Entitys;
using System.Data.Entity.Migrations;
using System.Reflection;

namespace RentHouse.Admin.App_Start
{
    public class LoggingActionFilter : ActionFilterAttribute
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(LoggingActionFilter));

        DBModel dBModel = new DBModel();

        DateTime date;
        DateTime Newdate;

        T_LogsAll logs = new T_LogsAll();
        // 记录操作开始，带参数信息
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var actionName = filterContext.ActionDescriptor.ActionName;
            var parameters = filterContext.ActionParameters;

            //获取运行前时间
            date = DateTime.Now;
            logs.CreateDateTime = date.ToString();
            // 记录参数信息
            var paramInfo = string.Join(", ", parameters.Select(p => $"{p.Key}: {p.Value??"Null"}"));
            log.Info($"Executing action: {controllerName}/{actionName} with parameters: {paramInfo}");

            logs.ControllerName = controllerName;
            logs.ActionName = actionName;
            logs.Parameters = paramInfo;
            //准备获取属性的值准备一个list
            //List<object> values = new List<object>();
            ////循环获取Dictionary的值组
            //foreach (var param in parameters.Values)
            //{
            //    //判断类型是否是string,不是string就利用反射进行循环
            //    if (param.GetType() != typeof(string))
            //    {
            //        // 使用反射获取属性信息
            //        PropertyInfo[] properties = param.GetType().GetProperties();
            //        //循环获取属性
            //        foreach (var property in properties)
            //        {
            //            // 获取属性值并添加到列表
            //            values.Add(property.GetValue(param));
            //        }
            //    }
            //    else
            //    {
            //        //如果是string就直接假如list
            //        values.Add(param);
            //    }
            //}
            ////把刚才的list转化为string
            //logs.Parameters = string.Join(",", values);


            base.OnActionExecuting(filterContext);

        }

        // 记录操作结束，带执行结果信息
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var actionName = filterContext.ActionDescriptor.ActionName;

            // 检查是否有异常
            if (filterContext.Exception != null)
            {
                log.Error($"Action {controllerName}/{actionName} threw an exception", filterContext.Exception);
                logs.Message = "error";
            }
            else
            {
                // 获取执行结果
                var result = filterContext.Result as JsonResult;
                if (result != null)
                {
                    log.Info($"Action {controllerName}/{actionName} executed successfully with result: {result.Data}");
                }
                else
                {
                    log.Info($"Action {controllerName}/{actionName} executed successfully.");
                }
                logs.Message = "success";
            }

            //获取运行前时间
            Newdate = DateTime.Now;
            //固定操作人ID
            logs.UserId = 56.ToString();
            //获取运行时间
            logs.Date = Newdate.Subtract(date).TotalMilliseconds.ToString();
            //保存日志到数据库
            dBModel.T_LogsAll.AddOrUpdate(logs);
            dBModel.SaveChanges();


            base.OnActionExecuted(filterContext);
        }


    }
}